package com.hzjh.base.utils.function

import android.graphics.drawable.Drawable
import android.widget.ImageView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.DecodeFormat
import com.bumptech.glide.load.engine.GlideException
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.RequestOptions
import com.bumptech.glide.request.target.Target


fun ImageView.load(
    url: String?,
    overrideW: Int? = null,
    overrideH: Int? = null,
    format: DecodeFormat? = null,
    placeholder: Drawable? = null,
    error: Drawable? = null,
    errorCall: (() -> Unit)? = null,
    onResourceReady: (() -> Unit)? = null,
) {

    var builder = Glide.with(this).load(url)
    val options = RequestOptions()
    if (overrideW != null && overrideH != null) {
        builder = builder.apply(options.override(overrideW, overrideH))
    }
    format?.let {
        builder = builder.apply(options.format(it))
    }
    builder = builder.placeholder(placeholder).error(error).dontTransform()
    if (errorCall != null || onResourceReady != null) {
        builder.listener(object : RequestListener<Drawable> {
            override fun onLoadFailed(
                e: GlideException?,
                model: Any?,
                target: Target<Drawable>?,
                isFirstResource: Boolean,
            ): Boolean {
                errorCall?.invoke()
                return false
            }

            override fun onResourceReady(
                resource: Drawable?,
                model: Any?,
                target: Target<Drawable>?,
                dataSource: DataSource?,
                isFirstResource: Boolean,
            ): Boolean {
                onResourceReady?.invoke()
                return false
            }

        })
    }
    builder.into(this)
}